import router from '@/router'
import MainRequest from './mainReq'
import type { MyResponse } from './type'
import useNotic from '@/hooks/useNotic'

const service = new MainRequest({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 20000,
  /**
   * 如有需要可主动传入拦截器覆盖默认拦截器
   * 写法如下
   */
  // 实例的请求拦截
  requestInterceptor: (config) => {
    return config
  },
  // 请求拦截异常捕获
  requestInterceptorCatch: (err) => {
    return err
  },
  // 实例的响应拦截
  responseInterceptor: (res) => {
    const myRes: MyResponse = { ...res, success: false, msg: '' }
    const resCode = res.data.code ? res.data.code + '' : ''
    switch (resCode) {
      case '200':
        myRes.success = true
        myRes.msg = res.data.msg ?? '请求成功'
        break
      case '401': // 登录超时/token失效
        // localStorage.clear()
        useNotic().error('登录超时')
        // router.push({ name: 'login' })
        break
      default:
        myRes.data.success = false
        myRes.msg = res.data.msg ?? '请求失败'
        useNotic().error(myRes.msg)
    }

    return myRes
  },
  // 实例的响应拦截异常捕获
  responseInterceptorCatch: (err) => {
    return err
  }
})
export default service
